package com.java.main.aop;

import java.lang.reflect.Method;

import com.java.main.constant.Errors;
import com.java.main.exception.HiBabyGlobalException;
import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Before;
import org.aspectj.lang.annotation.Pointcut;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Component;
import org.springframework.validation.BindingResult;
import org.springframework.validation.ObjectError;

import com.java.main.util.StringUtils;

/**
 * Controller 入参数据校验
 * 
 * @author naida
 *
 */
@Aspect
@Component
public class ControllerInputValidAop {
	private Logger log = LoggerFactory.getLogger(getClass());

	@Pointcut("execution(public * com.java.main.controller..*Controller.*(..))")
	public void checkToken() {
	}

	@Before("checkToken()")
	public void beforeCheckToken(JoinPoint point) {
		String className = point.getSignature().getDeclaringTypeName();
		if (!"BaseController".equals(className)) {// 设置排除方法不管用，暂时用这种解决办法
			// log.info("@Before：目标方法为：" +
			// point.getSignature().getDeclaringTypeName() + "."
			// + point.getSignature().getName());
			String errorMessage = "";
			BindingResult result = null;
			for (Object param : point.getArgs()) {
				if (param instanceof BindingResult) {
					result = (BindingResult) param;
					if (result.getAllErrors().size() > 0) {
						errorMessage = getAllErrorMessage(result);
						throw new HiBabyGlobalException(Errors.DATA_VALID_ERROR, errorMessage);
					}
				}
				param = setObjectStringpropertyTrim(param);
			}
			// log.info("@Before：参数为：" + Arrays.toString(point.getArgs()));
			// log.info("@Before：被织入的目标对象为：" + point.getTarget());
		}
	}

	String getAllErrorMessage(BindingResult result) {
		String resultStr = "";
		for (ObjectError error : result.getAllErrors()) {
			resultStr += error.getDefaultMessage() + ";";
		}
		return resultStr;
	}

	/**
	 * 将入参字符串两头空格去掉
	 * 
	 * @param object
	 */
	Object setObjectStringpropertyTrim(Object object) {
		String className = object.getClass().toString();
		if (className.indexOf("com.java.main") == -1) {
			return object;
		}
		log.info("当前处理对象为" + object.getClass());
		Class<?> cls = object.getClass();
		Method[] methods = cls.getDeclaredMethods();
		for (int i = 0; i < methods.length; i++) {
			Method method = methods[i];
			String name = method.getName();
			if (name.startsWith("get")) {
				name = name.substring(3);
				Object value = null;
				try {
					value = method.invoke(object, new Object[] {});
					if (value instanceof String && StringUtils.isNotEmpty(value.toString())) {
						String str = (String) value;
						str = str.trim();
						Method fieldSetMet = cls.getMethod("set" + name, String.class);
						fieldSetMet.invoke(object, new Object[] { str });
					}
				} catch (Exception e) {
					e.printStackTrace();
				}

			}
		}
		return object;
	}
}
